//
//  ConcurrentOperation.swift
//  ScaffoldKit
//
//  Created by SuXinDe on 2018/7/29.
//  Copyright © 2018年 su xinde. All rights reserved.
//

import Foundation

open class ConcurrentOperation: Operation {

    public var executionBlock: (() -> Void)?
    
    public init(executionBlock: (() -> Void)? = nil) {
        super.init()
        self.executionBlock = executionBlock
    }
    
    override open var isAsynchronous: Bool {
        return true
    }
    
    private var _executing = false {
        willSet {
            willChangeValue(forKey: "isExecuting")
        }
        didSet {
            didChangeValue(forKey: "isExecuting")
        }
    }
    
    override open var isExecuting: Bool {
        return _executing
    }
 
    private var _finished = false {
        willSet {
            willChangeValue(forKey: "isFinished")
        }
        didSet {
            didChangeValue(forKey: "isFinished")
        }
    }
    
    override open var isFinished: Bool {
        return _finished
    }
    
    override open func start() {
        _executing = true
        execute()
    }
    
    open func execute() {
        guard let executionBlock = executionBlock else {
            return
        }
        executionBlock()
        finish()
    }
    
    open func finish() {
        _executing = false
        _finished = true
    }
    
    open func pause() {}
    
    open func resume() {}
    
    public func addToShareQueueManager() {
        addToQueueManager(OperationQueueManager.shared)
    }
    
    public func addToQueueManager(_ queueManager:OperationQueueManager) {
        queueManager.addOperation(self)
    }
}
